package com.qf.service.impl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
//service层处理业务逻辑
public class UserServiceImpl implements UserService {
    private SqlSessionFactory sqlSessionFactory;
    //先获取会话工厂对象
    public void init() throws Exception {
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
    //mapper动态代理实现登录
    @Override
    public User login(User inputUser) throws Exception {
        init();
        //获取会话对象sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取UserDao映射文件
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        //执行userDao接口对应方法
        User user = userDao.login(inputUser);
        //关闭会话
        sqlSession.close();
        //将结果返回
        return user;
    }
    //mapper动态代理实现注册
    @Override
    public void reg(User inputUser) throws Exception {
        init();
        //获取会话对象sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取UserDao映射文件
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        //执行userDao接口对应方法
        userDao.reg(inputUser);
        //提交事务(增删改操作需提交事务数据库数据才会改变)
        sqlSession.commit();
        //关闭会话
        sqlSession.close();
    }
}
